<template>
  <el-dialog :title="!dataForm.id ? '调价新增':'调价修改'" :close-on-click-modal="false" :visible.sync="visible" center
    fullscreen>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form inline :model="dataForm" :rules="dataRule" ref="dataForm">
      <el-form-item label="价格组选择" prop="groupList">
        <el-select v-model="dataForm.priceGroupId " @change="groupSelectChange($event)" :disabled="this.priceFlag == 2">
          <el-option v-for="item in groupOptions" :key="item.id" :label="item.groupName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="调价方式">
        <el-input type="text" value="实时调价" readonly></el-input>
      </el-form-item>
      <el-form-item label="制单人" >
        <el-input v-model="this.userInfo.realName" readonly></el-input>
      </el-form-item>
      <el-form-item label="单据日期" >
        <el-input v-model="dataForm.createTime" readonly></el-input>
      </el-form-item>
    </el-form>
    <el-form label-width="40px">
        <el-form-item label="备注" prop="memo">
          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="dataForm.memo"></el-input>
        </el-form-item>
      </el-form>
    <el-form :inline="true">
      <el-form-item>
        <el-button type="primary" @click="addGoodsBySingle">选择商品</el-button>
      </el-form-item>
      <!-- <el-form-item><el-button type="primary">条码扫描</el-button></el-form-item> -->
      <el-form-item style="float: right;">
        <el-button type="danger" @click="delTableData">删除</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" ref="multipleTable" border v-loading="dataListLoading" header-cell-class-name="miui-header-cell-style" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="goodsCode" label="商品代码"></el-table-column>
      <el-table-column prop="goodsName" label="商品名称"></el-table-column>
      <el-table-column prop="supplyName" label="所属制造商"></el-table-column>
      <el-table-column prop="brandName" label="品种名称"></el-table-column>
      <el-table-column prop="spec" label="型号"></el-table-column>
      <el-table-column prop="oldPrice" label="现销售价格"> </el-table-column>
      <el-table-column prop="newPrice" label="调整价格">
        <template slot-scope="scope">
          <el-input v-model="scope.row.newPrice"></el-input>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保存</el-button>
      <el-switch v-model="dataForm.adStatus" active-text="保存并审核" inactive-value="0" active-value="1" style="margin-left: 15px;"></el-switch>
    </span>
    <search-supply v-if="supplyVisible" ref="supplyDialog" @refreshData="getSupplyData"></search-supply>
    <search-goods v-if="goodsVisible" ref="goodsDialog" @updateForm="getGoodsData"></search-goods>
  </el-dialog>
</template>

<script>
  import {mapGetters} from 'vuex'
  import { filterParams } from "@/util/tools"
  import { fetchList, getAdPriceObj, putObj, addObj } from "@/api/eims/retail-price-adjust"
  import { getGroupList } from "@/api/eims/price-group"
  import { getObj } from "@/api/admin/dept"
  import { getPriceGroupByDeptId } from "@/api/eims/price-group"
  import { getCtgList } from "@/api/eims/ctg"

  import SearchSupply from "@/components/business/SearchSupply"
  import SearchGoods from "@/components/business/SearchGoodsPrice"

  export default {
    data() {
      return {
				ischeck: false,
        visible: false,
        priceFlag: '',
        dataForm: {
          id: 0,
          adType: '1',
          adStatus: "0",
          priceGroupId: "",
          groupName: "",
          supplyId: "",
          supplyName: "",
          memo: "",
          createTime: '',
          detailList: []
        },
        ctgOptions: [],
        groupOptions: [],
        dataList: [],
        dataListLoading: false,
        dataRule: {
          priceGroupId: [{
            required: true,
            message: "请选择价格组"
          }]
        },
        supplySearchVisible: false,
        goodsListVisible: false,
        selectionList: [],
        supplyVisible: false,
        goodsVisible: false
      };
    },
    components: {
      SearchSupply,
      SearchGoods
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    methods: {
      init(id) {
        for(let key in this.dataForm){
          if(key != 'adStatus'){
            this.dataForm[key] = ''
          }else{
            this.dataForm[key] = '0'
          }
        }
        this.dataForm.adType = '1'
        this.getGroupList()
        this.getGoodsCtgList()
        this.getDate()
        this.getPriceGroupId()
        this.getPriceGroupFlag()
        this.dataForm.id = id || 0
        this.visible = true
        this.dataList = []
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields()
          if (this.dataForm.id) {
            this.dataListLoading = true
            getAdPriceObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data.data
                this.dataList = response.data.data.data.list
              }else{
                this.$message.error(response.data.msg)
              }
              this.dataListLoading = false
            })
          }
        })
      },
      //根据当前部门判断是否能调整所有价格组价格
      getPriceGroupFlag(){
        getObj(this.userInfo.lessDeptId).then(response =>{
          if(response.data.code == '0'){
            this.priceFlag = response.data.data.priceFlag
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //根据当前部门获取价格组id
      getPriceGroupId(){
        getPriceGroupByDeptId(this.userInfo.lessDeptId).then(response =>{
          if(response.data.code == '0'){
            this.dataForm.priceGroupId = response.data.data.groupId
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 商品类别改变时获取名字
      groupSelectChange($event) {
        this.groupOptions.forEach(item => {
          if (item.value == $event) {
            this.dataForm.groupName = item.groupName
          }
        })
      },
      // 打开商品列表弹窗
      addGoodsBySingle() {
        if (!this.dataForm.priceGroupId) {
          this.$message.warning("请选择价格组")
          return
        }
        let params = {
          priceGroupId: this.dataForm.priceGroupId
        }
        let data = {
          params: params,
          data: this.dataList
        }
        this.goodsVisible = true
        this.$nextTick(() => {
          this.$refs.goodsDialog.init(data)
        })
      },
      handleSelectionChange(val) {
        this.selectionList = val
      },
      // 删除选中的商品
      delTableData() {
        let arrIdList = this.selectionList.map(x => x.id)
        this.dataList = this.dataList.filter(x => !arrIdList.includes(x.id))
        this.$refs.multipleTable.clearSelection()
      },
      // 表单提交
      dataFormSubmit() {
        if(this.dataList.length<=0){
          this.$message.warning("请先选择商品")
        }
        for(let i=0;i<this.dataList.length;i++){
          if(!this.dataList[i].newPrice){
            this.$message.warning("请先填写调整价格!")
            return
          }
        }
				this.ischeck = true
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            let list = []
            this.dataList.forEach((item, index) => {
              item = filterParams(item)
              list.push(item)
            })
            this.dataForm.detailList = list;
            this.dataForm.createTime = ''
            if (this.dataForm.id) {
              putObj(filterParams(this.dataForm)).then(response => {
                if(response.data.code == '0'){
                  this.dataForm.adStatus == "1" ?
                    this.$message.success("修改并审核成功") :
                    this.$message.success("修改成功")
                  this.visible = false
                  this.$emit("refreshDataList")
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
								this.ischeck = false
							})
            } else {
              addObj(filterParams(this.dataForm)).then(response => {
                if(response.data.code == '0'){
                  this.dataForm.adStatus == "1" ?
                    this.$message.success("新增并审核成功") :
                    this.$message.success("新增成功")
                  this.visible = false
                  this.$emit("refreshDataList")
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
								this.ischeck = false
							})
            }
          }else{
						this.ischeck = false
					}
        })
      },
      // 获取价格组列表
      getGroupList() {
        getGroupList().then(response => {
          if(response.data.code == '0'){
            this.groupOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //  获取商品类别列表
      getGoodsCtgList() {
        getCtgList().then(response => {
          if(response.data.code == '0'){
            this.ctgOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //  商品类别改变事件
      ctgChange(val) {
        this.dataForm.supplyId = ""
        this.dataForm.supplyName = ""
      },
      //  选择制造商
      choiceSupply() {
        let data = {
          ctgId: this.dataForm.ctgId
        }
        this.supplyVisible = true
        this.$nextTick(() => {
          this.$refs.supplyDialog.init(data)
        })
      },
      //  获取制造商信息
      getSupplyData(data) {
        this.dataForm.supplyId = data.id
        this.dataForm.supplyName = data.name
      },
      //  获取商品信息
      getGoodsData(data) {
        let list = []
        data.forEach(item => {
          item.goodsName = item.goodsName ? item.goodsName : item.name
          item.goodsCode = item.goodsCode ? item.goodsCode : item.code
          item.oldPrice = (item.oldPrice || item.oldPrice == 0) ? item.oldPrice : item.price
          item.newPrice = (item.newPrice || item.newPrice == 0) ? item.newPrice : item.price
          item.goodsId = item.id
          list.push(item)
        });
        this.dataList = JSON.parse(JSON.stringify(list))
        this.dataForm.detailList = list
      },
      //获取当前日期
      getDate() {
        let nowDate = new Date()
        let sysTime = {
            year: nowDate.getFullYear(),
            month: (nowDate.getMonth() + 1) < 10 ? "0" +(nowDate.getMonth() + 1) : (nowDate.getMonth() + 1),
            date: nowDate.getDate() < 10 ? "0" +nowDate.getDate() : nowDate.getDate(),
        }
        this.dataForm.createTime = sysTime.year + '-' + sysTime.month + '-'  + sysTime.date
      }
    }
  }
</script>
